/*
 * SimpleModal Contact Form
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: contact.js 113 2008-03-15 15:36:21Z emartin24 $
 *
 */
 
/**
 * Google Maps 表示
 */
function load() {

    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"),
            {size:new GSize(406, 200)});
        var latlng = new GLatLng(35.507456, 139.617585);
        map.setCenter(latlng, 13, G_NORMAL_MAP);
        //map.addControl(new GMapTypeControl());
        map.addControl(new GSmallMapControl());
        
        // マーカー
        var marker = new GMarker(latlng);
        map.addOverlay(marker);
            
        //地図移動で十字アイコン追随と、座標を表示
        GEvent.addListener(map, "move", function() { 
           marker.setPoint(map.getCenter());
           showLatLon();
        });
        
        // marker が示す座標を表示
        showLatLon = function (){
            point = map.getCenter()
            $('#contact-lat').val(point.x);
            $('#contact-lon').val(point.y);
        };
        
        showLatLon();
    }
}

function closeMessage() {
    var msg = $('#contact-container .contact-message');
    msg.fadeOut(400, function () {
        msg.css({'display':'none'});
        var edit = $('#edit');
        edit.fadeIn(200, function () {
            edit.css({'display': 'inline'});
        });
        $('#contact-container .contact-content').css({'height': '500px'});
    });
}

$(document).ready(function () {
	$('#contactLink, #contactForm input:eq(0)').click(function (e) {
		e.preventDefault();
		// load the contact form using ajax
		$.get("statics/input_entry.html", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				overlayId: 'contact-overlay',
				containerId: 'contact-container',
				onOpen: contact.open,
				onShow: contact.show,
				onClose: contact.close
			});
		});
	});

	// preload images
	var img = ['cancel.png', 'form_bottom.gif', 'form_top.gif',
        'form_top_ie.gif','loading.gif','send.png'];
	$(img).each(function () {
		var i = new Image();
		i.src = 'img/' + this;
	});
});

var contact = {
	message: null,
	open: function (dialog) {

		// googlemaps
		load();

		
		// add padding to the buttons in firefox/mozilla
		if ($.browser.mozilla) {
			$('#contact-container .contact-button').css({
				'padding-bottom': '2px'
			});
		}
		// input field font size
		if ($.browser.safari) {
			$('#contact-container .contact-input').css({
				'font-size': '.9em'
			});
		}
		
		var title = $('#contact-container .contact-title').html();
		$('#contact-container .contact-title').html('読み込み中...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#contact-container .contact-content').animate({
						height: 500
					}, function () {
						$('#contact-container .contact-title').html(title);
						$('#contact-container form').fadeIn(200, function () {
							$('#contact-container #contact-name').focus();

							// fix png's for IE 6
							if ($.browser.msie && $.browser.version < 7) {
								$('#contact-container .contact-button').each(function () {
									if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
										var src = RegExp.$1;
										$(this).css({
											backgroundImage: 'none',
											filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
										});
									}
								});
							}
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#contact-container .contact-send').click(function (e) {
			e.preventDefault();
			// validate form
			if (contact.validate()) {
				$('#contact-container .contact-memo').fadeOut(function () {
					$('#contact-container .contact-memo').removeClass('contact-error').empty();
				});
				$('#contact-container .contact-title').html('登録中...');
				$('#contact-container form').fadeOut(200);
				$('#contact-container .contact-content').animate({
					height: '80px'
				}, function () {
					$('#contact-container .contact-loading').fadeIn(200, function () {
						$.ajax({
							url: '/add',
							//data: $('#contact-container form').serialize() + '&action=send',
                            data: {
                                'title' : $('#contact-title').val(),
                                'published' : $('#contact-published').checked,
                                'lon' : $('#contact-lon').val(),
                                'lat' : $('#contact-lat').val(),
                                'memo' : $('#contact-memo').val()
                            },
							type: 'post',
							dataType: 'jsonp',
							complete: function (xhr) {
								$('#contact-container .contact-loading').fadeOut(200, function () {
								    $('#contact-container .contact-title').html('Thank you!');
								    $('#contact-container').fadeOut(200);  
                                $('#contact-container .contact-content').animate({
                                    height: 40
                                }, function () {
                                    dialog.data.fadeOut(200, function () {
                                        dialog.container.fadeOut(200, function () {
                                            dialog.overlay.fadeOut(200, function () {
                                                $.modal.close();
                                                $('#test').load('/test');
                                            });
                                        });
                                    });
                                });
								});
								location.href = "/";
							},
							error: contact.error
						});
					});
				});
			}
			else {
				if ($('#contact-container .contact-message:visible').length > 0) {
					var msg = $('#contact-container .contact-memo div');
					msg.fadeOut(200, function () {
						msg.empty();
						contact.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#contact-container .contact-memo').animate({
						height: '30px'
					}, contact.showError());
				}
			}
		});
	},
	close: function (dialog) {
		$('#contact-container .contact-memo').fadeOut();
		$('#contact-container .contact-title').html('終了...');
		$('#contact-container form').fadeOut(200);
		$('#contact-container .contact-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		contact.message = '';
		if (!$('#contact-container #contact-title').val()) {
			contact.message += '名前が入力されていません。';
		}
		
		if (!$('#contact-container #contact-lon').val()) {
			contact.message += '経度が入力されていません。';
		}
		
		if (!$('#contact-container #contact-lat').val()) {
			contact.message += '緯度が入力されていません。';
		}
		
		/*
		var email = $('#contact-container #contact-email').val();
		if (!email) {
			contact.message += 'Email is required. ';
		}
		else {
			if (!contact.validateEmail(email)) {
				contact.message += 'Email is invalid. ';
			}
		}
        */
        
		if (contact.message.length > 0) {
		    
		    $('#contact-container .contact-content').css({
				'height': '550px'
			});
			
			contact.message = '<a href="javascript:closeMessage();" class="close"><img src="/img/info.png" />' + contact.message + '</a>';
			return false;
		}
		else {
			return true;
		}
	},
	showError: function () {
		$('#contact-container .contact-message')
			.html($('<div class="contact-error">').append(contact.message))
			.fadeIn(600);
		$('#edit').css({'display': 'none'});
		$('#contact-container .contact-content').css({'height': '200px'});
	}
};
